import 'dart:convert';

import 'package:flutter_keep_book/core/extensions/map.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'local_storage_url.dart';

abstract class LocalStorageKey {
  /// 是否第一次弹出隐私弹窗
  static const isFirstShowPrivacy = "is_first_show_privacy";

  /// 是否同意隐私弹窗
  static const isAgreePrivacy = "isAgreePrivacy";
  //是否上报激活
  static const reportActivation = "reportActivation";

  /// 用户登录 token
  static const userToken = "user_token";

  /// 是否审核中
  static const isAuditing = "is_auditing";

  /// 客服链接
  static const customerService = "customer_service";

  /// 客服链接跳转方式
  static const customerServiceType = "customer_type";

  /// 用户协议
  static const userAgreement = "user_agreement";

  /// 隐私政策
  static const privacyPolicy = "privacy_policy";

  /// 支付协议
  static const paymentAgreement = "payment_agreement";

  /// 运费规则
  static const deliveryPriceRule = "delivery_price_rule";

  /// 玩法规则
  static const rulesOfPlay = "box_drew_rules";

  /// 魔盒SDK列表
  static const boxSdkList = "box_sdk_list";

  /// 魔盒第三方信息共享清单
  static const commonBill = "common_bill";

  ///是否勾选过确认付款协议
  static const isPayStatus = "is_pay_status";

  /// 道具卡弹窗日期。（用于判断「今天」是否弹过窗）
  static const itemCardPopupDate = 'item_card_popup_date';

  /// 安装后第一次打开 App 的时间戳 (秒)
  static const firstOpenTimestamp = "first_open_timestamp";

  /// 指向各种域名对应的请求api
  static const goodsSourceHostname = "goods_source_hostname";

  ///非当天第一次弹出push弹窗 false:已弹出
  static const isNotShowOpenAppPush = 'isShowOpenAppPush';

  ///天天领券后首次弹出 false:已弹出
  static const isNotShowCouPonPush = 'isShowCouPonPush';

  ///领取道具卡后首次弹出 false:已弹出
  static const isNotShowCardPush = 'isShowCardPush';

  /// 地址数据版本
  static const addressRegionVersion = 'region_version';

  ///手指是否出现
  static const isShowFinger = 'isSHowFinger';

  ///试玩开关
  static const trialSwitch = 'trial_switch';

  /// 详情规则视频弹窗。（用于判断「今天」是否弹过窗）
  static const detailsVideoShowDate = 'details_video_show_date';

  /// 是否弹过活动push false:已弹出
  static const isNotShowMarketingPush = 'isNotShowMarketingPush';

  ///推送物流开关
  static const pushLogisticsSwitch = 'push_logistics_switch';

  ///推送服务开关
  static const pushServiceSwitch = 'push_service_switch';

  /// 推送活动开关
  static const pushMarketingSwitch = 'push_marketing_switch';

  /// 戳戳乐 - 第一次进入页面指引
  static const shouldShowPokePageGuidance = 'should_show_poke_page_guidance';

  /// 戳戳乐 - 第一次选中盒子指引
  static const shouldShowPokeNumberGuidance = 'should_show_poke_number_guidance';

  /// 是否展示戳戳乐选项
  static const isShowPokeGame = 'is_show_poke_game';

  /// 新人 7 天乐盒子开盒结果「去仓库」指引
  static const newcomer7DaysResultPageWarehouseGuidance = 'newcomer_7_days_result_page_warehouse_guidance';

  /// 仓库 - 新人提货/兑换指引
  static const warehouseNewcomerGuidance = 'warehouse_newcomer_guidance';

  /// 仓库 - 新人去商城兑换指引
  static const warehouseShopGuidance = 'warehouse_shop_guidance';

  ///首页 是否展示榜单
  static const isShowStarRanking='is_show_star_ranking';


  static const baseUrl='base_url';
}

/// 本地轻量级存储数据
class LocalStorage {
  static SharedPreferences? prefs;

  static initSP() async {
    prefs = await SharedPreferences.getInstance();
  }

  static saveString(String key, String value) {
    prefs?.setString(key, value);
  }

  static saveInt(String key, int value) {
    prefs?.setInt(key, value);
  }

  static saveBool(String key, bool value) {
    prefs?.setBool(key, value);
  }

  static bool? getBool(String key) {
    return prefs?.getBool(key);
  }

  static String? getString(String key) {
    return prefs?.getString(key);
  }

  static String? getBaseUrl(String key) {
    return prefs?.getString(key);
  }

  static int? getInt(String key) {
    return prefs?.getInt(key);
  }

  static remove(String key) {
    prefs?.remove(key);
  }

  /// 用户 token
  static String? get token => getString(LocalStorageKey.userToken);

  static Future<void> setUserToken(String? value) async {
    if (value != null && value.isNotEmpty) {
      await prefs?.setString(LocalStorageKey.userToken, value);
    } else {
      await prefs?.remove(LocalStorageKey.userToken);
    }
  }

  /// 更新版本配置信息
  static updateEdition(Map<String, dynamic> json) {
    LocalStorage.isAuditing = json.boolValue(LocalStorageKey.isAuditing) ?? false;
    LocalStorage.customerService = json.stringValue(LocalStorageKey.customerService);
    LocalStorage.customerServiceType = json.stringValue(LocalStorageKey.customerServiceType);
    LocalStorageUrl.userAgreement = json.stringValue(LocalStorageKey.userAgreement);
    LocalStorageUrl.privacyPolicy = json.stringValue(LocalStorageKey.privacyPolicy);
    LocalStorageUrl.paymentAgreement = json.stringValue(LocalStorageKey.paymentAgreement);
    LocalStorageUrl.deliveryPriceRule = json.stringValue(LocalStorageKey.deliveryPriceRule);
    LocalStorageUrl.rulesOfPlay = json.stringValue(LocalStorageKey.rulesOfPlay) ?? "";
    LocalStorageUrl.commonBill = json.stringValue(LocalStorageKey.commonBill);
    LocalStorageUrl.boxSdkList = json.stringValue(LocalStorageKey.boxSdkList);
    LocalStorageUrl.goodsSourceHostname = jsonDecode(
      json.stringValue(LocalStorageKey.goodsSourceHostname) ?? '',
    );
    LocalStorage.addressRegionVersion = json.intValue(LocalStorageKey.addressRegionVersion);
    LocalStorage.trialSwitch = json.boolValue(LocalStorageKey.trialSwitch);
    LocalStorage.isShowPokeGame = json.boolValue(LocalStorageKey.isShowPokeGame) ?? false;
    LocalStorage.isShowStarRanking = json.boolValue(LocalStorageKey.isShowStarRanking) ?? false;
  }

  /// 是否审核中
  static bool get isAuditing => getBool(LocalStorageKey.isAuditing) ?? false;

  static set isAuditing(bool value) => saveBool(LocalStorageKey.isAuditing, value);

  static set setBaseUrl(String value) => saveString(LocalStorageKey.baseUrl, value);

  /// 客服链接
  static String? get customerService => getString(LocalStorageKey.customerService);

  static set customerService(String? value) {
    if (value != null && value.isNotEmpty) {
      saveString(LocalStorageKey.customerService, value);
    } else {
      remove(LocalStorageKey.customerService);
    }
  }

  /// 客服链接跳转类型。
  /// weixin: 微信客服，需要跳转微信 App；
  /// qidian: 腾讯企点，App 内用 WebView 打开。
  static String? get customerServiceType => getString(LocalStorageKey.customerServiceType);
  static set customerServiceType(String? value) {
    if (value != null && value.isNotEmpty) {
      saveString(LocalStorageKey.customerServiceType, value);
    } else {
      remove(LocalStorageKey.customerServiceType);
    }
  }

  /// 是否第一次展示隐私弹窗
  static bool get isFirstShowPrivacy => getBool(LocalStorageKey.isFirstShowPrivacy) ?? true;

  static set isFirstShowPrivacy(bool value) => saveBool(LocalStorageKey.isFirstShowPrivacy, value);

  /// 是否同意隐私弹窗
  static bool get isAgreePrivacy => getBool(LocalStorageKey.isAgreePrivacy) ?? false;

  static bool get isReportActivation => getBool(LocalStorageKey.reportActivation) ?? false;

  static set isAgreePrivacy(bool value) => saveBool(LocalStorageKey.isAgreePrivacy, value);

  static set isReportActivation(bool value) => saveBool(LocalStorageKey.reportActivation, value);

  /// 是否第一次勾选支付协议
  static set isPayStatus(bool value) => saveBool(LocalStorageKey.isPayStatus, value);

  static bool get isPayStatus => getBool(LocalStorageKey.isPayStatus) ?? false;

  /// 道具卡弹窗日期。格式：yyyy-MM-dd => 2023-02-06。
  /// 用于判断「今天」是否弹过窗。
  static String? get itemCardPopupDate => getString(
        LocalStorageKey.itemCardPopupDate,
      );

  static set itemCardPopupDate(String? value) {
    if (value != null && value.isNotEmpty) {
      saveString(LocalStorageKey.itemCardPopupDate, value);
    } else {
      remove(LocalStorageKey.itemCardPopupDate);
    }
  }

  /// 安装后第一次打开 App 的时间戳 (秒)
  static int? get firstOpenTimestamp => getInt(
        LocalStorageKey.firstOpenTimestamp,
      );

  static set firstOpenTimestamp(int? value) {
    if (value != null) {
      saveInt(LocalStorageKey.firstOpenTimestamp, value);
    } else {
      remove(LocalStorageKey.firstOpenTimestamp);
    }
  }

  /// 是否第一次打开 App。
  static bool get isFirstOpenApp => _isFirstOpenApp;
  static set isFirstOpenApp(bool value) => _isFirstOpenApp = value;

  /// 地址数据版本。（时间戳，秒）
  static int? get addressRegionVersion => getInt(LocalStorageKey.addressRegionVersion);
  static set addressRegionVersion(int? value) {
    if (value == null) {
      remove(LocalStorageKey.addressRegionVersion);
    } else {
      saveInt(LocalStorageKey.addressRegionVersion, value);
    }
  }

  ///试玩开关
  static bool get trialSwitch => LocalStorage.getBool(LocalStorageKey.trialSwitch) ?? true;

  static set trialSwitch(bool? value) {
    LocalStorage.saveBool(LocalStorageKey.trialSwitch, value ?? true);
  }

  /// 戳戳乐tab
  static bool get isShowPokeGame => getBool(LocalStorageKey.isShowPokeGame) ?? false;

  static set isShowPokeGame(bool value) => saveBool(LocalStorageKey.isShowPokeGame, value);

  /// 戳戳乐tab
  static bool get isShowStarRanking => getBool(LocalStorageKey.isShowStarRanking) ?? false;

  static set isShowStarRanking(bool value) => saveBool(LocalStorageKey.isShowStarRanking, value);

  /// 详情页视频弹窗。格式：yyyy-MM-dd => 2023-02-06。 盒子ID
  /// 用于判断「今天」是否弹过窗。
  static String? getDetailsVideoShowDate(int boxId) => getString(
        '${LocalStorageKey.detailsVideoShowDate}_$boxId',
      );

  static void setDetailsVideoShowDate(int boxId, String? value) {
    if (value != null && value.isNotEmpty) {
      saveString('${LocalStorageKey.detailsVideoShowDate}_$boxId', value);
    } else {
      remove('${LocalStorageKey.detailsVideoShowDate}_$boxId');
    }
  }

  /// 戳戳乐 - 第一次进入页面指引
  static bool get shouldShowPokePageGuidance => getBool(LocalStorageKey.shouldShowPokePageGuidance) ?? true;

  static set shouldShowPokePageGuidance(bool value) => saveBool(LocalStorageKey.shouldShowPokePageGuidance, value);

  /// 戳戳乐 - 第一次选中盒子指引
  static bool get shouldShowPokeNumberGuidance => getBool(LocalStorageKey.shouldShowPokeNumberGuidance) ?? true;

  static set shouldShowPokeNumberGuidance(bool value) => saveBool(LocalStorageKey.shouldShowPokeNumberGuidance, value);

  /// 开盒结果页 - 新人七天乐盒子「去仓库」指引
  static bool get shouldShowNewcomer7DaysResultPageWarehouseGuidance =>
      getBool(LocalStorageKey.newcomer7DaysResultPageWarehouseGuidance) ?? true;
  static set shouldShowNewcomer7DaysResultPageWarehouseGuidance(bool value) =>
      saveBool(LocalStorageKey.newcomer7DaysResultPageWarehouseGuidance, value);

  /// 仓库 - 新人提货/兑换指引
  static bool get shouldShowWarehouseNewcomerGuidance => (getBool(LocalStorageKey.warehouseNewcomerGuidance) ?? true);
  static set shouldShowWarehouseNewcomerGuidance(bool value) =>
      saveBool(LocalStorageKey.warehouseNewcomerGuidance, value);

  /// 仓库 - 新人去商城指引
  static bool get shouldShowWarehouseShopGuidance => (getBool(LocalStorageKey.warehouseShopGuidance) ?? true);
  static set shouldShowWarehouseShopGuidance(bool value) =>
      saveBool(LocalStorageKey.warehouseShopGuidance, value);
}

bool _isFirstOpenApp = false;
